<template>
  <div class="container mx-auto px-4 py-8">
    <div class="share-container">
      <div class="page-header">
        <h1 class="page-title">我的分享</h1>
        <el-button 
          type="primary" 
          class="comment-wall-btn"
          @click="$router.push('/share/comment-wall')"
          round
        >
          <el-icon class="mr-2"><ChatLineSquare /></el-icon>
          返回评论墙
        </el-button>
      </div>

      <!-- 顶部操作栏 -->
      <div class="flex flex-wrap gap-4 items-center justify-between mb-8">
        <div class="flex items-center gap-4">
          <el-input
            v-model="searchQuery"
            placeholder="搜索分享..."
            class="w-64 search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
          <el-select
            v-model="selectedTags"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择标签"
            class="w-64 tag-select"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.tagId"
              :label="tag.tagName"
              :value="tag.tagId"
            />
          </el-select>
        </div>
        <el-button 
          type="primary" 
          class="publish-btn"
          @click="handlePublishClick"
        >
          <el-icon class="mr-1"><Plus /></el-icon>发布分享
        </el-button>
      </div>

      <!-- 内容列表 -->
      <div v-loading="loading" class="grid grid-cols-1 gap-6">
        <el-empty v-if="shareList.length === 0" description="暂无数据" />
        
        <el-card 
          v-for="share in shareList" 
          :key="share.shareId" 
          class="post-card"
          @click="navigateToDetail(share.shareId)"
        >
          <div class="flex items-start gap-4">
            <!-- 用户信息 -->
            <div class="flex-shrink-0">
              <el-avatar 
                :size="48" 
                :src="getUserAvatar(share)"
                @click.stop="navigateToUserProfile(share.userId)"
                class="user-avatar"
              />
            </div>

            <!-- 帖子内容 -->
            <div class="flex-grow">
              <div class="flex items-center justify-between mb-2">
                <div>
                  <span 
                    class="font-semibold hover:text-blue-600 cursor-pointer username"
                    @click.stop="navigateToUserProfile(share.userId)"
                  >
                    {{ share.createBy }}
                  </span>
                </div>
                <span class="text-gray-500 text-sm">{{ formatTime(share.createTime) }}</span>
              </div>

              <p class="text-gray-600 mb-4 line-clamp-3 content">{{ share.content }}</p>

              <!-- 标签 -->
              <div class="flex flex-wrap gap-2 mb-4 tags">
                <el-tag
                  v-for="tagId in share.tagsId"
                  :key="tagId"
                  size="small"
                  effect="plain"
                  class="tag-item"
                  @click.stop="filterByTag(tagId)"
                >
                  {{ getTagName(tagId) }}
                </el-tag>
              </div>

              <!-- 互动栏 -->
              <div class="flex items-center gap-6 text-gray-500 interaction-bar">
                <button 
                  class="interaction-btn comment-btn"
                  @click.stop="navigateToDetail(share.shareId)"
                >
                  <el-icon><ChatRound /></el-icon>
                  <span>{{ share.commentCount || 0 }} 评论</span>
                </button>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="mt-8 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 发布对话框 -->
      <el-dialog
        v-model="showPublishDialog"
        title="发布分享"
        width="600px"
        destroy-on-close
        class="publish-dialog"
      >
        <el-form 
          ref="publishFormRef"
          :model="publishForm"
          :rules="publishRules"
          label-width="80px"
        >
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="publishForm.content"
              type="textarea"
              :rows="4"
              placeholder="分享你的经验和想法..."
              maxlength="1000"
              show-word-limit
              class="publish-textarea"
            />
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="publishForm.tags"
              multiple
              placeholder="选择标签"
              class="w-full"
            >
              <el-option
                v-for="tag in tagOptions"
                :key="tag.tagId"
                :label="tag.tagName"
                :value="tag.tagId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelPublish" class="cancel-btn">取消</el-button>
            <el-button type="primary" :loading="publishing" @click="handlePublish" class="confirm-btn">
              发布
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  ChatRound,
  ChatLineSquare
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  getShareList, 
  getShareByTag, 
  getAllTags, 
  addShare
} from '@/api/share'
import { useUserStore } from '@/store/user'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const router = useRouter()
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const searchQuery = ref('')
const selectedTags = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showPublishDialog = ref(false)
const publishing = ref(false)
const shareList = ref([])
const tagOptions = ref([])
const defaultAvatar = '/src/assets/user-avatar.svg'

// 发布表单
const publishFormRef = ref(null)
const publishForm = ref({
  content: '',
  tags: []
})

// 表单验证规则
const publishRules = {
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '内容长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请选择至少一个标签', trigger: 'change' },
    { type: 'array', max: 3, message: '最多选择 3 个标签', trigger: 'change' }
  ]
}

// 获取用户头像
const getUserAvatar = (share) => {
  // 优先使用分享中的用户头像
  if (share.avatar) {
    return share.avatar
  }
  
  // 如果是当前用户，使用当前用户头像
  if (userStore.isLoggedIn && share.userId === userStore.userInfo?.userId) {
    return userStore.userInfo?.avatar || defaultAvatar
  }
  
  // 默认返回通用头像
  return defaultAvatar
}

// 获取标签名称
const getTagName = (tagId) => {
  const tag = tagOptions.value.find(t => t.tagId === tagId)
  return tag ? tag.tagName : tagId
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

// 获取分享列表
const fetchShareList = async () => {
  loading.value = true
  try {
    const res = await getShareList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value
    })
    
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取分享列表失败')
    }
  } catch (error) {
    console.error('获取分享列表失败:', error)
    ElMessage.error('获取分享列表失败')
  } finally {
    loading.value = false
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await getAllTags()
    if (res.code === 0 || res.code === 200) {
      tagOptions.value = res.data || []
    } else {
      console.error('获取标签列表失败:', res.message)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 根据标签筛选
const filterByTagId = async (tagId) => {
  loading.value = true
  try {
    const res = await getShareByTag(tagId)
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data || []
      total.value = shareList.value.length
    } else {
      ElMessage.error(res.message || '获取标签分享失败')
    }
  } catch (error) {
    console.error('获取标签分享失败:', error)
    ElMessage.error('获取标签分享失败')
  } finally {
    loading.value = false
  }
}

// 根据标签筛选
const filterByTag = (tagId) => {
  if (!selectedTags.value.includes(tagId)) {
    selectedTags.value = [tagId]
    filterByTagId(tagId)
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchShareList()
}

// 处理发布点击
const handlePublishClick = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  showPublishDialog.value = true
}

// 处理发布
const handlePublish = async () => {
  if (!publishFormRef.value) return
  
  try {
    await publishFormRef.value.validate()
    publishing.value = true
    
    const data = {
      userId: userStore.userInfo?.userId,
      createBy: userStore.userInfo?.nickname || userStore.userInfo?.username,
      content: publishForm.value.content,
      tags: publishForm.value.tags,
      avatar: userStore.avatar || userStore.userInfo?.avatar
    }
    
    const res = await addShare(data)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('发布成功')
      showPublishDialog.value = false
      resetPublishForm()
      fetchShareList()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  } finally {
    publishing.value = false
  }
}

// 重置发布表单
const resetPublishForm = () => {
  publishForm.value = {
    content: '',
    tags: []
  }
  if (publishFormRef.value) {
    publishFormRef.value.resetFields()
  }
}

// 取消发布
const cancelPublish = () => {
  showPublishDialog.value = false
  resetPublishForm()
}

// 导航到详情页
const navigateToDetail = (id) => {
  router.push(`/share/${id}`)
}

// 导航到用户主页
const navigateToUserProfile = (userId) => {
  router.push(`/user/${userId}`)
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchShareList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchShareList()
}

// 监听标签变化
watch(selectedTags, (tags) => {
  if (tags.length > 0) {
    filterByTagId(tags[0])
  } else {
    fetchShareList()
  }
})

onMounted(() => {
  fetchTags()
  fetchShareList()
})
</script>

<style scoped>
.share-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #4d7cfe;
  position: relative;
  padding-bottom: 0.5rem;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 60px;
  height: 3px;
  background: linear-gradient(to right, #4d7cfe, #6a95fe);
  border-radius: 3px;
}

.comment-wall-btn {
  transition: all 0.3s ease;
}

.comment-wall-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(77, 124, 254, 0.2);
}

.search-input {
  border-radius: 8px;
}

.tag-select {
  border-radius: 8px;
}

.post-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-bottom: 1.5rem;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

.user-avatar {
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.username {
  font-weight: 600;
  transition: color 0.3s ease;
}

.content {
  color: #303133;
  line-height: 1.6;
}

.tags {
  margin: 0.5rem 0;
}

.tag-item {
  transition: all 0.3s ease;
  cursor: pointer;
}

.tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.interaction-bar {
  border-top: 1px solid #f0f2f5;
  padding-top: 0.75rem;
  margin-top: 0.75rem;
}

.interaction-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  border-radius: 6px;
  transition: all 0.3s ease;
  background-color: transparent;
  border: none;
  color: #606266;
  cursor: pointer;
}

.interaction-btn:hover {
  background-color: #f0f2f5;
  color: #4d7cfe;
}

.comment-btn:hover {
  background-color: #e6f7ff;
  color: #1890ff;
}

.publish-btn {
  transition: all 0.3s ease;
}

.publish-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(77, 124, 254, 0.2);
}

.publish-dialog {
  border-radius: 12px;
}

.publish-textarea {
  border-radius: 8px;
}

.confirm-btn {
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  .share-container {
    padding: 1rem;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .comment-wall-btn {
    width: 100%;
  }
}
</style> 